package com.gitee.wsl.compose.ext.text

import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.input.TextFieldValue

fun TextFieldValue.copySpanStyles(source: TextFieldValue) =
    this.copy(
        annotatedString = buildAnnotatedString {
            append(text)
            source.annotatedString.spanStyles.forEach {
                if (it.start >= 0 && it.end > it.start && it.end < text.length) {
                    addStyle(it.item, it.start, it.end)
                }
            }
        }
    )

internal const val TAB_LENGTH = 4
internal const val TAB_CHAR = "\t"

fun TextFieldValue.updateIndentations(handleIndentations: Boolean) =
    if (handleIndentations && text.contains(TAB_CHAR)) {
        val result = text.replace(TAB_CHAR, " ".repeat(TAB_LENGTH))
        this.copy(text = result, TextRange(selection.start + TAB_LENGTH - 1))
    } else {
        this
    }